<template>
  <div class="form_wapper rainbow">
    <el-card class="box-card">
      <datepicker />
    </el-card>
    <el-card class="box-card">
      <p>动态校验</p>
      <el-form
        ref="elForm"
        :model="formData"
        :inline="true">
        <el-row>
          <el-col :span="24">
            <template v-for="(k,index) in formData.lists">
              <div :key="index">
                <el-col
                  :span="6">
                  <el-form-item
                    :ref="index+'concatWay'"
                    label="联系方式"
                    :prop="'lists.' + index +'.concatWay'"
                    :rules=" { required: true, message: '请选择联系方式', trigger: 'blur' }">
                    <el-select
                      v-model="k.concatWay"
                      @change="changeWays(k.concatWay,index)">
                      <template v-for="ways in concatWays">
                        <el-option
                          :key="ways.code"
                          :label="ways.name"
                          :value="ways.code" />
                      </template>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col
                  :span="6">
                  <el-form-item
                    :ref="index+'concatValue'"
                    :prop="'lists.' + index +'.concatValue'"
                    :rules="k.rules">
                    <el-input v-model="k.concatValue" />
                  </el-form-item>
                </el-col>
              </div>
            </template>
          </el-col>
        </el-row>
      </el-form>
      <el-row
        type="flex"
        justify="center">
        <el-button
          @click="save">提交</el-button>
        <el-button
          type="primary"
          @click="addNewWay">新增联系方式</el-button>
      </el-row>
    </el-card>
    <el-card class="box-card">
      <p>动态更改是否必选项</p>
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm">
        <el-form-item
          label="活动名称"
          prop="name"
          :required="isHaveTo">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item
          label="活动区域"
          prop="region">
          <el-select
            v-model="ruleForm.region"
            placeholder="请选择活动区域"
            style="width:100%">
            <el-option
              label="必填"
              value="0" />
            <el-option
              label="非必填"
              value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="submitForm('ruleForm')">立即创建</el-button>
        </el-form-item>
      </el-form>

    </el-card>
    <el-card class="box-card filter-wrapper">
      <p>动态指令过滤输入</p>
      <el-input
        v-model="inputSpaceFilter"
        v-input-filter
        placeholder="空格无法输入" />
      <el-input
        v-model="inputIntFilter"
        v-input-filter:int
        placeholder="只能输入整数" />
      <el-input
        v-model="inputPriceFilter"
        v-input-filter:price
        placeholder="只能输入价格" />
      <el-input
        v-model="inputSpecialFilter"
        v-input-filter:special
        placeholder="过滤特殊字符" />
      <el-input
        v-model="inputPhoneFilter"
        v-input-filter:phone
        placeholder="只能输入手机号" />
      <el-input
        v-model="inputUrlFilter"
        v-input-filter:url
        placeholder="只能输入网址" />
      <el-input
        :value="form.name"
        maxlength="5"
        placeholder="全局自定义指令/过滤特殊/字符长度5"
        @input="e => form.name = filterInput(e)" />
    </el-card>
    <el-card class="box-card dynamicForm">
      <p>动态增加表单区块，名称一、二、三...递增</p>
      <div class="center_content">
        <el-form
          ref="ruleData"
          :model="ruleData"
          label-width="100px"
          :rules="rules">
          <el-row>
            <el-col :span="24">
              <el-form-item
                label="公司名称">
                <el-input
                  v-model="ruleData.companyName"
                  placeholder="请输入公司的名称" />
              </el-form-item>
            </el-col>
            <template
              v-for="(item, index) in ruleData.financialProduct"
              class="product_box">
              <div :key="index">
                <el-col :span="24">
                  <el-form-item :label="`产品${titleIdx[index]}详情`" />
                </el-col>
                <el-col
                  :span="9">
                  <el-form-item
                    label="产品名称"
                    :prop="`financialProduct.${index}.productName`"
                    :rules="financialProductRules.productName">
                    <el-input
                      v-model="item.productName"
                      placeholder="请输入产品名称" />
                  </el-form-item>
                </el-col>
                <el-col
                  :span="9">
                  <el-form-item
                    label="产品数量"
                    :prop="`financialProduct.${index}.productNum`"
                    :rules="financialProductRules.productNum">
                    <el-input
                      v-model="item.productNum"
                      placeholder="请输入产品数量" />
                  </el-form-item>
                </el-col>
                <template
                  v-for="(homes, indexHomes) in item.dockingPerson">
                  <div :key="indexHomes">
                    <el-col
                      :span="9">
                      <el-form-item
                        label="对接人"
                        :prop="`financialProduct.${index}.dockingPerson.${indexHomes}.dockingName`"
                        :rules="dockingPerson.dockingName">
                        <el-input
                          v-model="homes.dockingName"
                          placeholder="请填写对接人" />
                      </el-form-item>
                    </el-col>
                    <el-col
                      :span="9">
                      <el-form-item
                        label="政策"
                        :prop="`financialProduct.${index}.dockingPerson.${indexHomes}.makeWay`"
                        :rules="dockingPerson.makeWay">
                        <el-input
                          v-model="homes.makeWay"
                          placeholder="请填写政策" />
                      </el-form-item>
                    </el-col>
                    <el-col
                      :span="6">
                      <el-form-item label="">
                        <el-button
                          type="primary"
                          @click="addRebatePolicy(item.dockingPerson, indexHomes,index)">添加</el-button>
                        <el-button
                          @click="deleteRebatePolicy(item.dockingPerson, indexHomes,index)">删除</el-button>
                      </el-form-item>
                    </el-col>
                  </div>
                </template>
              </div>
            </template>
          </el-row>
          <div
            class="btn_submit">
            <el-form-item>
              <el-button
                type="primary"
                @click="onSubmit(ruleData)">确认保存</el-button>
              <el-button
                @click="addProduct">增加产品</el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios'
import datepicker from './datepicker'
import inputFilter from '@/directives/inputFilter.js' // 引入
// 重复的校验规则:必填
const baseRule = [
  { required: true, message: '请填写联系方式', trigger: 'blur' }
]
export default {
  name: 'HelloWorld',
  directives: {
    inputFilter
  },
  components: {
    datepicker
  },
  data() {
    // 验证活动名称的函数
    const validateName = (rule, value, callback) => {
      // 当活动名称为空值且为必填时，抛出错误，反之通过校验
      if (this.ruleForm.name === '' && this.isHaveTo) {
        callback(new Error('请输入活动名称'))
      } else {
        callback()
      }
    }
    return {
      ruleForm: {
        name: '',
        region: ''
      },
      rules: {
        name: [{ validator: validateName }],
        region: [
          { required: true, message: '请选择类型', trigger: 'blur' }
        ]
      },
      idx: 0,
      titleIdx: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十', '二十一', '二十二', '二十三', '二十四', '二十五', '二十六', '二十七', '二十八', '二十九', '三十'],
      ruleData: {
        companyName: '', // 公司名称
        financialProduct: [
          // 产品数组
          {
            productName: '内控管理系统', // 产品名称
            productNum: 10,
            dockingPerson: [
              // 对接人
              {
                dockingName: '魏工', // 联系人
                makeWay: '唯二减一' // 计提条件
              }
            ]
          }
        ]
      },
      financialProductRules: {
        productName: [
          { required: true, message: '请输入产品名称', trigger: 'blur' }
        ],
        productNum: [
          { required: true, message: '请输入产品数量', trigger: 'blur' }
        ]
      },
      dockingPerson: {
        dockingName: [
          { required: true, message: '请输入联系人姓名', trigger: 'blur' }
        ],
        makeWay: [
          { required: true, message: '请输入计提条件', trigger: 'blur' }
        ]
      },
      form: {
        name: ''
      },
      inputSpaceFilter: '',
      inputIntFilter: '',
      inputPriceFilter: '',
      inputSpecialFilter: '',
      inputPhoneFilter: '',
      inputUrlFilter: '',
      formData: {
        lists: [{
          concatWay: '', // 联系方式：电话/手机
          concatValue: '', // 具体的联系方式的值
          rules: baseRule// 基础校验规则:必填
        }]

      },
      inputRules: {// 设置好需要的校验规则
        telephone: { pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误', trigger: 'blur' },
        phone: { pattern: /^\d{10,12}$/, message: '座机号格式错误', trigger: 'blur' },
        QQ: { pattern: /^[1-9][0-9]{4,14}$/, message: 'QQ格式错误', trigger: 'blur' },
        mail: { pattern: /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/, message: '邮箱格式错误', trigger: 'blur' }
      },
      dyRoutes: {},
      concatWays: [
        { name: '手机', code: 'telephone' },
        { name: '座机', code: 'phone' },
        { name: 'QQ', code: 'QQ' },
        { name: '邮箱', code: 'mail' }
      ]
    }
  },
  computed: {
    isHaveTo: function() {
      return this.ruleForm.region !== '1'
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log('已提交表单')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    addRebatePolicy(item, index, parentIndex) {
      this.idx++
      this.ruleData.financialProduct[parentIndex].dockingPerson.push(
        {
          dockingName: '刘' + this.titleIdx[this.idx], // 联系人
          makeWay: '推介费增加' + (this.idx * 10) + '%' // 计提条件
        }
      )
      console.log(item, index, parentIndex)
    },
    deleteRebatePolicy(item, index, parentIndex) {
      this.ruleData.financialProduct[parentIndex].dockingPerson.splice(index, 1)
      console.log(item, index, parentIndex)
    },
    addProduct() {
      this.idx++
      this.ruleData.financialProduct.push(
        {
          productName: '进销系统' + this.titleIdx[this.idx], // 产品名称
          productNum: 10 + this.idx,
          dockingPerson: [
            // 对接人
            {
              dockingName: '王' + this.titleIdx[this.idx], // 联系人
              makeWay: '满' + this.titleIdx[this.idx] + '减一' // 计提条件
            }
          ]
        }
      )
    },
    onSubmit(formName) {
      this.$refs['ruleData'].validate(valid => {
        if (valid) {
          console.log(this.ruleData)
          try {
            axios.post('http://localhost:3000/api/saveForm', this.ruleData).then(res => {
              console.log(res)
            })
          } catch (e) {
            console.log(e)
          }
        } else {
          return false
        }
      })
    },
    addNewWay() { // 新增联系方式
      this.formData.lists.push({
        concatWay: '',
        concatValue: '',
        rules: baseRule
      })
    },

    changeWays(data, index) {
      // 有值的话将自己的校验手动清空
      if (data) {
        const getRefWays = index + 'concatWay'
        this.$refs[getRefWays][0].clearValidate()
      }
      // 将值清空
      this.formData.lists[index].concatValue = ''
      // 去除联系方式的格式校验
      const getRefs = index + 'concatValue'
      this.$refs[getRefs][0].clearValidate()
      // 给表单加上新的校验
      this.formData.lists[index].rules = [this.inputRules[data]].concat(baseRule)
    },
    save() {
      this.$refs.elForm.validate(async(valid) => {
        if (valid) {
          const methosData = await this.getJson()
          console.log(methosData)
          this.$message({
            message: '表单提交成功，查看提交值请打开F12',
            type: 'success'
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getJson() { // 只取到要提交的值
      return new Promise((resolve, reject) => {
        const tempJson = JSON.parse(JSON.stringify(this.formData.lists))
        tempJson.map((item) => {
          delete item.rules
          return item
        })
        resolve(tempJson)
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.filter-wrapper .el-input {
  margin: 10px auto;
}
hr{
  margin-bottom: 60px;
}
.el-card{
  margin: 10px 0;
}
</style>
